package com.zeros.latte.net.callback;

import android.os.Handler;

import com.zeros.latte.apps.Latte;
import com.zeros.latte.net.RestCreator;
import com.zeros.latte.ui.LatteLoader;
import com.zeros.latte.ui.LoaderStyle;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * retrofit特有callbackon 2018/1/30.
 */

public class RequestCallbacks implements Callback<String> {

    private final IRequest REQUEST;
    private final ISuccess SUCCESS;
    private final IFailure FAILURE;
    private final IError ERROR;
    private final LoaderStyle LOADER_STYLE;
//    Handler尽量是static避免内存泄漏
//    private static final Handler HANDLER = Latte.getHandler();//为使loading更显示，添加延迟
    private static final Handler HANDLER = new Handler();//为使loading更显示，添加延迟

    public RequestCallbacks(IRequest REQUEST, ISuccess SUCCESS, IFailure FAILURE,
                            IError ERROR, LoaderStyle style) {
        this.REQUEST = REQUEST;
        this.SUCCESS = SUCCESS;
        this.FAILURE = FAILURE;
        this.ERROR = ERROR;
        this.LOADER_STYLE = style;
    }

    @Override
    public void onResponse(Call<String> call, Response<String> response) {
        if (response.isSuccessful()) {
//            call已经执行
            if (call.isExecuted()) {
//                success的回调--判断空指针
                if (SUCCESS != null) {
                    SUCCESS.onSuccess(response.body());
                }
            }
        } else {
            if (ERROR != null) {
                ERROR.onError(response.code(), response.message());
            }
        }

        onRequestFinish();
    }

    @Override
    public void onFailure(Call<String> call, Throwable t) {
        if (FAILURE != null) {
            FAILURE.onFailure();
        }
//        请求结束
        if (REQUEST != null) {
            REQUEST.onRequestEnd();
        }
        //        loading结束
        onRequestFinish();
    }

    private void onRequestFinish() {
//        final long delayed=Latte.getConfigurations(Con)
        if (LOADER_STYLE != null) {
            HANDLER.postDelayed(new Runnable() {
                @Override
                public void run() {
                    RestCreator.getParams().clear();
                    LatteLoader.stopLoading();
                }
            }, 1000);
        }

    }


}
